package com.sh.utils.Qiniu;

import android.util.Log;
import com.qiniu.android.common.Zone;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.utils.StringUtils;
import com.sh.utils.BackgroundManagerUtils;
import lombok.Data;

import java.io.File;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

import static com.sh.struts.GlobalDefine.QINIU_DOMAIN;

@Data
public class QiniuUploadUtils {
    private static final String TAG = "qiniuUitls";
    private static QiniuUploadUtils instance;
    private UploadManager uploadManager;

    private QiniuUploadUtils() {
        Configuration config = new Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .responseTimeout(30)// 服务器响应超时。默认60秒
                //.recorder(recorder)           // recorder分片上传时，已上传片记录器。默认null
                //.recorder(recorder, keyGen)   // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(Zone.zone1)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();

        // 重用uploadManager。一般地，只需要创建一个uploadManager对象
        uploadManager = new UploadManager(config);
    }

    public static QiniuUploadUtils getInstance() {
        if (instance == null) {
            //加同步安全
            synchronized (QiniuUploadUtils.class) {
                if (instance == null) {
                    instance = new QiniuUploadUtils();
                }
            }
        }
        return instance;
    }

    public void uploadFile(File file, String fileName, String token) {
        uploadManager.put(file, fileName, token,
                (key, info, res) -> {
                    //res包含hash、key等信息，具体字段取决于上传策略的设置
                    if (info.isOK()) {
                        Log.i("qiniu", "Upload Success");
                    } else {
                        Log.i("qiniu", "Upload Fail");
                        //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                    }
                    Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                }, null);
    }

    /**
     * @param file
     * @param uploadPath
     * @return
     */
    public String syncUploadFile(File file, String uploadPath) {
        CountDownLatch latch = new CountDownLatch(1);
        String token = BackgroundManagerUtils.getUploadToken();
        AtomicReference<String> retValue = new AtomicReference<>("");
        if (!StringUtils.isNullOrEmpty(token)) {
            uploadManager.put(file, uploadPath, token, ((key, info, response) -> {
                if (info.isOK()) {
                    retValue.set(String.format("%s/%s", QINIU_DOMAIN, uploadPath));
                } else {
                    retValue.set("");
                }
                latch.countDown();
            }), null);
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return retValue.get();
    }
}
